/**
 * 解析响应头字符串为对象
 * @param {string} headerString
 * @returns {Object}
 */
function parseHeaders(headerString) {
  const headers = {}
  if (!headerString) return headers

  const lines = headerString.split('\r\n')
  for (const line of lines) {
    if (line) {
      const [key, value] = line.split(': ')
      if (key && value) {
        headers[key.toLowerCase()] = value
      }
    }
  }
  return headers
}

/**
 * 基于 Promise 的 AJAX 请求封装
 * @param {Object} config - 请求配置
 * @param {string} config.url - 请求URL
 * @param {'GET'|'POST'|'PUT'|'DELETE'|'PATCH'} [config.method='GET'] - HTTP方法
 * @param {Object} [config.headers] - 请求头对象
 * @param {Object|string} [config.data] - 请求数据
 * @param {Object|string} [config.params] - 请求参数
 * @param {'json'|'text'|'blob'|'arraybuffer'|'document'} [config.responseType='json'] - 响应类型
 * @param {number} [config.timeout=30000] - 超时时间(毫秒)
 * @returns {Promise} 返回响应数据或错误对象
 */
export default function req(config) {
  return new Promise((resolve, reject) => {
    let { url, method = 'GET', headers = {}, data = null, params = {}, responseType = 'json', timeout = 30000 } = config

    url += `${url.indexOf('?') ? '' : '?'}${new URLSearchParams(params).toString()}`

    // 创建 XHR 实例
    const xhr = new XMLHttpRequest()

    // 初始化请求
    xhr.open(method, url, true)

    // 设置响应类型
    xhr.responseType = responseType

    // 设置超时
    xhr.timeout = timeout

    // 设置请求头
    Object.keys(headers).forEach((key) => {
      xhr.setRequestHeader(key, headers[key])
    })
    xhr.setRequestHeader('authorization', localStorage.getItem('authorization'))

    // 事件处理
    xhr.onload = function () {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve({
          status: xhr.status,
          statusText: xhr.statusText,
          data: xhr.response,
          headers: parseHeaders(xhr.getAllResponseHeaders()),
        })
      } else {
        reject({
          status: xhr.status,
          statusText: xhr.statusText,
          data: xhr.response,
          error: `Request failed with status ${xhr.status}`,
        })
      }
    }

    xhr.onerror = function () {
      reject({
        status: 0,
        statusText: 'Network Error',
        error: 'Network request failed',
      })
    }

    xhr.ontimeout = function () {
      reject({
        status: 0,
        statusText: 'Timeout',
        error: `Request timed out after ${timeout}ms`,
      })
    }

    // 处理请求数据
    let sendData = data
    if (data && typeof data === 'object' && !(data instanceof FormData)) {
      if (!headers['Content-Type']) {
        xhr.setRequestHeader('Content-Type', 'application/json')
      }
      sendData = JSON.stringify(data)
    }

    // 发送请求
    xhr.send(sendData)
  })
}

req.get = (url, params, config = {}) => req({ url, params, ...config })
req.post = (url, data, config = {}) => req({ url, data, method: 'POST', ...config })
